import _ from "lodash";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
import type { TagProps, ButtonType, ElForm } from "element-plus";
import Table from "@/components/table/index.vue";
import { reactive, onUnmounted, onActivated, onDeactivated } from "vue";
import type { Component } from "vue";
import { ElNotification } from "element-plus";
import type { baTableApi } from "@/utils/common"; //封装好的table 请求api类
import { getArrayKey, handleTree, filterParams } from "@/utils/common";
import useCurrentInstance from "@/utils/useCurrentInstance"; //mitt全局事件总线bus
import { deviceTableList } from "../../virtual";
import router from "@/router/index";
import { useFactoryEquipment } from "@/store/backend/FactoryM/equipmentUnit";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import { useBomRoute } from "@/store/backend/BomM/bomRoute";
import { useBomM } from "@/store/backend/BomM/bomM";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useProductionWorkOrder } from "@/store/backend/ProductionPlan/workOrder";
import { useFactoryEquipmenClass } from "@/store/backend/FactoryM/equipmentSchedule";
import { useFactorySchedule } from "@/store/backend/FactoryM/factorySchedule";
import { useStoreWarePurchase } from "@/store/backend/StoreroomM/Purchase";
import { useSupplierInfo } from "@/store/backend/Supplier/Info";

/* 通用搜索类型 */
interface ComSearch {
  form: any;
  fieldData: Map<string, any>;
}

interface anyObj {
  [key: string]: any;
}
// module TableRowInterface {
//   export interface TableRow {}
// }

/* 表格行 */
export interface TableRow extends anyObj {
  children?: TableRow[];
}
/* baTable类型 */
interface BaTable {
  ref?: typeof Table;
  pk?: string;
  data?: TableRow[];
  remark?: string | null;
  loading?: boolean;
  expandAll?: boolean;
  selection?: TableRow[];
  dblClickNotEditColumn?: (string | undefined)[];
  column: TableColumn[];
  total?: number;
  filter?: any;
  defaultOrder?: { prop: string; order: string };
  dragSortLimitField?: string;
  acceptQuery?: boolean;
  showComSearch?: boolean;
  extend?: any;
}

/* baTableForm */
interface BaTableForm {
  ref?: InstanceType<typeof ElForm> | undefined;
  labelWidth?: number;
  operate?: string;
  operateIds?: string[];
  items?: any;
  submitLoading?: boolean;
  defaultItems?: any;
  loading?: boolean;
  extend?: any;
}

/* BaTable前置处理函数(前置埋点) */
interface BaTableBefore {
  getIndex?: Function;
  postDel?: Function;
  requestEdit?: Function;
  onTableDblclick?: Function;
  toggleForm?: Function;
  onSubmit?: Function;
  onTableAction?: Function;
  onTableHeaderAction?: Function;
  mount?: Function;
  [key: string]: Function | undefined;
}

/* BaTable后置处理函数(后置埋点) */
interface BaTableAfter {
  getIndex?: Function;
  postDel?: Function;
  requestEdit?: Function;
  onTableDblclick?: Function;
  toggleForm?: Function;
  onSubmit?: Function;
  onTableAction?: Function;
  onTableHeaderAction?: Function;
  mount?: Function;
  [key: string]: Function | undefined;
}

/* 链接打开方式 */
type aTarget = "_blank" | "_self";

/* 通用搜索操作符支持的值  SQL数据库条件查询支持的运算符*/
type OperatorStr =
  | "=" // 等于，默认值
  | "<>" //不等于
  | ">"
  | ">="
  | "<"
  | "<="
  | "LIKE" //like称为模糊查询，支持%或下划线匹配
  | "NOT LIKE"
  | "IN" //包含，相当于多个or
  | "NOT IN" //不在这个范围中
  | "RANGE" // 范围，将生成两个输入框 以输入最小值和最大值
  | "NOT RANGE"
  | "NULL" // 是否为NULL，将生成单个复选框
  | "NOT NULL"
  | "FIND_IN_SET";

/* 通用搜索事件返回的Data */
interface comSearchData {
  field: string;
  val: string;
  operator: string;
  render: string;
}

/* 表格列 */
export interface TableColumn extends ElTableColumn {
  // 是否显示
  show?: boolean | string;
  // 是否在下拉菜单的复选框显示 默认为true显示
  enableColumnDisplayControl?: boolean;
  // 渲染为:icon|switch|image|images|tag|url|datetime|buttons|customTemplate|customRender
  render?:
    | "icon"
    | "switch"
    | "switchAccess"
    | "image"
    | "images"
    | "tag"
    | "tags"
    | "url"
    | "datetime"
    | "buttons"
    | "customTemplate"
    | "customRender";
  // 操作按钮组
  buttons?: OptButton[];
  // 渲染为Tag时:el-tag 组件的主题
  effect?: TagProps["effect"];
  // 渲染为Tag时:el-tag 组件的size
  size?: TagProps["size"];
  // 自定义数据:比如渲染为Tag时,可以指定不同值时的Tag的Type属性 { open: 'success', close: 'info' }
  custom?: any;
  // 谨慎使用：自定义渲染模板，方法可返回html内容，请确保返回内容是xss安全的
  customTemplate?: (row: TableRow, field: TableColumn, value: any) => string;
  // 自定义组件/函数渲染
  customRender?: string | Component;
  // 渲染为链接时,链接的打开方式
  target?: aTarget;
  // 渲染为:url 时的点击事件
  click?: Function;
  // 渲染为 datetime 时的格式化方式,字母可以自由组合:y=年,m=月,d=日,h=时,M=分,s=秒，默认：yyyy-mm-dd hh:MM:ss
  timeFormat?: string;
  // 默认值
  default?: any;
  // 值替换数据,如{open: '开'}
  replaceValue?: any;
  // 使用了 render 属性时,渲染前对字段值的预处理方法，请返回新值
  renderFormatter?: (
    row: TableRow,
    field: TableColumn,
    value: any,
    index: number
  ) => any;
  // 通用搜索操作符,默认值为=,false禁用此字段通用搜索,支持的操作符见下定义
  operator?: boolean | OperatorStr;
  // 通用搜索框的placeholder
  operatorPlaceholder?: string;
  // 公共搜索渲染方式:上方的 render=tag|switch 时公共搜索也会渲染为下拉，数字会渲染为范围筛选，时间渲染为时间选择器等
  comSearchRender?: "remoteSelect" | "select" | "date" | "customRender";
  // 公共搜索自定义组件/函数渲染
  comSearchCustomRender?: string | Component;
  // 远程属性
  remote?: {
    pk?: string;
    field?: string;
    params?: any;
    multiple?: boolean;
    remoteUrl: string;
  };
}

/* 表格右侧操作按钮 */
export interface OptButton {
  disabled?: (row: TableRow, field: TableColumn) => boolean;
  // 渲染方式:tipButton=带tip的按钮,confirmButton=带确认框的按钮,moveButton=移动按钮
  render: string;
  name: string;
  title?: string;
  text?: string;
  class?: string;
  type: ButtonType;
  icon: string;
  popconfirm?: any;
  disabledTip?: boolean;
  // 自定义点击事件
  click?: (row: TableRow, field: TableColumn) => void;
  // 按钮是否显示，请返回布尔值
  display?: (row: TableRow, field: TableColumn) => boolean;
  attr: any;
}

/*
 * ElTableColumn可用属性
 * 未找到方法直接导出tableColumn的props类型定义
 * https://element-plus.org/zh-CN/component/table.html#table-column-attributes
 */
interface ElTableColumn {
  type?: "selection" | "index" | "expand";
  index?: number | Function;
  label?: string;
  "column-key"?: string;
  prop?: string;
  width?: string | number;
  "min-width"?: string | number;
  fixed?: string | boolean;
  "render-header"?: Function;
  sortable?: string | boolean;
  "sort-method"?: Function;
  "sort-by"?: Function;
  "sort-orders"?: string[] | null[];
  resizable?: boolean;
  formatter?: Function;
  "show-overflow-tooltip"?: boolean;
  align?: "left" | "center" | "right";
  "header-align"?: "left" | "center" | "right";
  "class-name"?: string;
  "label-class-name"?: string;
  selectable?: Function;
  "reserve-selection"?: boolean;
  filters?: { key: string; value: string }[];
  "filter-placement"?: string;
  "filter-multiple"?: boolean;
  "filter-method"?: Function;
  "filtered-value"?: any[];
}

export default class baTable {
  //table api
  public api;
  // 表格是否激活，多表格共存时，激活的表格才能触发事件
  public activate: boolean;
  //表格状态
  public table: BaTable = reactive({
    ref: undefined,
    // 主键字段
    pk: "id",
    // 数据源
    data: [],
    // 路由remark
    remark: null,
    // 表格加载状态
    loading: false,
    // 是否展开所有子项
    expandAll: false,
    // 选中项
    selection: [],
    // 不需要'双击编辑'的字段
    dblClickNotEditColumn: [undefined],
    // 列数据
    column: [],
    // 数据总量
    total: 0,
    // 字段搜索,快速搜索,分页等数据
    filter: {
      pageNum: 1,
      pageSize: 10,
      // 快速搜索，指定字段请在对应后端控制器内定义，默认为id
      // quick_search: "快速搜索关键词",
      // 公共搜索
      // search: [
      //   {
      //     field: "title",
      //     val: "搜索标题字段",
      //     operator: "LIKE",
      //     render: "tags",
      //   },
      // ],
    },
    // 拖动排序限位字段:例如拖动行pid=1,那么拖动目的行pid也需要为1
    dragSortLimitField: "pid",
    // 接受url的query参数并自动触发通用搜索
    acceptQuery: true,
    // 显示公共搜索
    showComSearch: false,
    // 扩展数据
    extend: {},
  });

  /* 表单状态-s */
  public form: BaTableForm = reactive({
    // 表单ref，new时无需传递
    ref: undefined,
    // 表单label宽度
    labelWidth: 160,
    // 当前操作:add=添加,edit=编辑
    operate: "",
    // 被操作数据ID,支持批量编辑:add=[0],edit=[1,2,n]
    operateIds: [],
    // 表单数据
    items: {},
    // 提交按钮状态
    submitLoading: false,
    // 默认表单数据(添加)
    defaultItems: {},
    // 表单字段加载状态
    loading: false,
    // 扩展数据
    extend: {},
  });

  // 通用搜索数据-需要响应性
  public comSearch: ComSearch = reactive({
    form: {},
    fieldData: new Map(),
  });
  // BaTable前置处理函数列表(前置埋点)
  public before;
  // BaTable后置处理函数列表(后置埋点)
  public after;

  constructor(
    api: baTableApi,
    table: BaTable,
    form: BaTableForm = {},
    before: BaTableBefore = {},
    after: BaTableAfter = {}
  ) {
    this.api = api;
    this.activate = true;
    this.table = Object.assign(this.table, table);
    this.form = Object.assign(this.form, form);
    this.before = before;
    this.after = after;

    const route = useRoute();
    //通用搜索初始化 动态生成搜索栏 与搜索表单数据
    this.initComSearch(!_.isUndefined(route) ? route.query : {});
  }

  /* 获取表格选择项的id数组 */
  getSelectionIds() {
    const ids: string[] = [];
    this.table.selection?.forEach((item) => {
      ids.push(item[this.table.pk!]);
    });
    console.log("获取表格选择项的id数组", ids);

    return ids;
  }

  /**
   * 表格顶栏按钮事件统一响应
   * @param event 事件:refresh=刷新,edit=编辑,delete=删除,quick-search=快速查询
   * @param data 携带数据
   */

  //前置请求
  runBefore(funName: string, args: any = {}) {
    if (
      this.before &&
      this.before[funName] &&
      typeof this.before[funName] == "function"
    ) {
      return this.before[funName]!({ ...args }) === false ? false : true;
    }
    return true;
  }

  //后置请求
  runAfter(funName: string, args: any = {}) {
    if (
      this.after &&
      this.after[funName] &&
      typeof this.after[funName] == "function"
    ) {
      return this.after[funName]!({ ...args }) === false ? false : true;
    }
    return true;
  }

  /* API请求方法-s */
  // 查看
  getIndex = (type: string) => {
    if (this.runBefore("getIndex") === false) return;
    this.table.loading = true;
    /**
     * 等通用搜索初始化完之后生成新的this.table.filter搜索字段
     */
    this.table.data = deviceTableList.data.list;
    this.table.total = deviceTableList.data.total;
    // this.table.remark = deviceTableList.data.remark;
    this.table.loading = false;
    this.runAfter("getIndex", { deviceTableList });
  };
  //list 菜单/用户管理list数据待处理
  getList = (type: string) => {
    if (this.runBefore("getList") === false) return;
    this.table.loading = true;
    console.log("getList菜单/用户管理", this.comSearch.form);
    return this.api
      .list(type, this.comSearch.form)
      ?.then((res: any) => {
        if (this.api.controllerUrl === "/system/menu") {
          this.table.data = handleTree(res.data, "menuId", "", "");
        } else if (this.api.controllerUrl === "/system/dept") {
          this.table.data = handleTree(res.data, "deptId", "", "");
        } else if (this.api.controllerUrl === "/system/region") {
          this.table.data = handleTree(res.rows, "areaId", "", "");
        } else if (this.api.controllerUrl === "/system/memoryInfo") {
          this.table.data = handleTree(res.rows, "memoryId", "", "");
        } else if (this.api.controllerUrl === "/system/site") {
          this.table.data = handleTree(res.rows, "siteId", "", "");
        } else if (this.api.controllerUrl === "/system/dict/data/type") {
          this.table.data = res.data;
        } else {
          this.table.data = res.rows;
        }
        console.log("list 菜单/用户管理list数据待处理", this.table);

        this.table.total = res.total;
        this.table.loading = false;
        this.runAfter("getList", { res });
      })
      .catch(() => {
        //无权限或其他错误关闭loading效果
        this.table.loading = false;
      });
  };
  //list 菜单/用户管理list数据待处理
  getSearch = (type: string) => {
    if (this.runBefore("getList") === false) return;
    this.table.loading = true;
    return this.api
      .search(type, this.comSearch.form)
      ?.then((res: any) => {
        if (this.api.controllerUrl === "/system/menu") {
          this.table.data = handleTree(res.data, "menuId", "", "");
        } else if (this.api.controllerUrl === "/system/dept") {
          this.table.data = handleTree(res.data, "deptId", "", "");
        } else if (this.api.controllerUrl === "/system/region") {
          this.table.data = handleTree(res.rows, "areaId", "", "");
        } else if (this.api.controllerUrl === "/system/dict/data/type") {
          this.table.data = res.data;
        } else {
          this.table.data = res.rows;
        }
        this.table.total = res.total;
        this.table.loading = false;
        this.runAfter("getList", { res });
      })
      .catch(() => {
        //无权限或其他错误关闭loading效果
        this.table.loading = false;
      });
  };
  //实时监控历史模块
  getHistory = (type: string, name: string) => {
    console.log("触发");
    if (this.runBefore("getHistory") === false) return;
    this.table.loading = true;
    return this.api
      .history(type, this.comSearch.form)
      ?.then((res: any) => {
        this.table.data = res.rows;
        this.table.total = res.total;
        this.table.loading = false;
        this.runAfter("getHistory", { res });
      })
      .catch(() => {
        //无权限或其他错误关闭loading效果
        this.table.loading = false;
      });
  };
  // 删除
  postDel = (ids: string[]) => {
    if (this.runBefore("postDel", { ids }) === false) return;
    this.api.del(ids).then((res) => {
      this.onTableHeaderAction("refresh", {});
      this.runAfter("postDel", { res });
    });
  };
  // 编辑
  requestEdit = (id: any) => {
    if (this.runBefore("requestEdit", { id }) === false) return;
    this.form.loading = true;
    this.form.items = {};
    return this.api
      .edit(id)
      .then((res: any) => {
        if (this.api.controllerUrl === "/system/user") {
          //用户管理的编辑表单
          res.data.postIds = res.postIds ? res.postIds : []; //编辑用户获取用户岗位信息
          res.data.roleIds = res.roleIds ? res.roleIds : []; //编辑用户获取用户角色信息
          res.data.regions = res.regions ? res.regions : []; //编辑用户获取用户区域信息
          res.data.companyid = res.companyid ? res.companyid : 0; //为了编辑用户时提交表单时不为null
        } else if (this.api.controllerUrl === "/system/role") {
          //roleSort双向绑定了el-input-number 需要number类型的数字 这里转换一下
          res.data.roleSort = Number(res.data.roleSort);
        } else if (this.api.controllerUrl === "/system/equipment") {
          //设备接入模块 所属企业select组件需要的institution字段是number类型 后端返回的是字符串 这里转换一下
          res.data.institution = Number(res.data.institution);
        }
        // } else if (this.api.controllerUrl === "/system/company") {
        //   /**
        //    * 企业管理模块 所属区域tree组件需要的region字段是number类型 后端返回的是字符串
        //    *  判断是否为空
        //    *  先将字符串分割成字符串数组在转换为number数组
        //    */
        //   res.data.region = res.data.region
        //     ? Array.from(res.data.region.split(","), (item) => Number(item))
        //     : [];
        // }
        this.form.loading = false;
        this.form.items = res.data;
        this.runAfter("requestEdit", { res });
      })
      .catch(() => {
        this.form.loading = false;
      });
  };
  //导出
  exportTable = async (ids: string[]) => {
    if (this.runBefore("exportTable") === false) return;
    if (!window.location.href.includes("Monitordetail")) {
      //普通模块
      this.api.export(this.comSearch.form).then((res) => {
        this.onTableHeaderAction("refresh", {});
        this.runAfter("exportTable");
      });
    } else {
      const monitor = useBackendMonitor();
      console.log("是历史数据模块", monitor.historyFilter);
      //newfilter整合了条件搜索
      let newfilter = await filterParams(monitor.historyFilter);
      this.api.export(newfilter).then((res) => {
        this.onTableHeaderAction("refreshistory", {});
        this.runAfter("exportTable");
      });
    }
  };
  //批量下单&&检查产能外加提示
  batchOrder = async (ids: string[]) => {
    this.getProcessArr(ids);
  };
  //批量获取计划工序数组
  getProcessArr = (ids: string[]) => {
    const routePlan = useBomRoute();
    let processList: any[] = []; //计划工序数组
    let promisesList: any[] = [];

    console.log("批量获取计划", this.table.selection);
    //批量生成工单
    // this.addWorkOrder(this.table.selection);
    //一组计划数据传递给接口进行产能判断
    this.allAddWorkOrder(this.table.selection);
    //前端计算产能
    // this.table.selection?.forEach((item) => {
    //   promisesList.push(
    //     routePlan
    //       .getRouteList({
    //         materialCode: item.productCode,
    //         materialType: item.materialType,
    //       })
    //       .then((res: any) => {
    //         res.rows.map((i: any) => {
    //           i.parentCode =
    //             i.parentCode == "0" ? i.parentCode : item.productCode;
    //           i.productName = item.productName; //产品名称
    //           i.planNum = item.name; //产品计划号，批次号
    //           // i.orderNum *= item.planQuantity; //总量
    //           i.prepareTime *= item.planQuantity; //准备时间
    //           i.afterTime *= item.planQuantity; //收尾时间
    //           i.productTime *= item.planQuantity; //加工时间
    //           i.startTime = item.startTime; //计划开始时间
    //           i.endTime = new Date(item.endTime).getTime(); //计划结束时间
    //         });
    //         processList.push(...res.rows);
    //       })
    //       .catch((err: any) => {})
    //   );
    // });
    Promise.all(promisesList).then((res: any) => {
      console.log("批量获取计划工序数组", processList);
      this.capacityCheck(processList);
    });
  };
  allAddWorkOrder = (data: any) => {
    const workOrder = useProductionWorkOrder();
    let newData: any[] = [];
    for (let i = 0; i < data.length; i++) {
      if (data[i].planState < 1 || data[i].planState == 5) {
        newData.push(data[i]);
      }
    }
    workOrder
      .confirmWorkOrder(newData)
      .then((res: any) => {
        ElNotification({
          type: "success",
          message: "工单已生成，可在工单管理进行派工",
        });
      })
      .catch((err: any) => {});
  };
  //批量生成工单
  addWorkOrder = async (data: any) => {
    console.log("批量生成工单批量生成工单", data);
    const promises = data.map(this.createWorkOrder);
    await Promise.all(promises);
    ElNotification({
      type: "success",
      message: "工单已生成，可在工单管理进行派工",
    });
    // const workOrder = useProductionWorkOrder();
    // for (let i = 0; i < data.length; i++) {
    //   workOrder.addPlanOrder(data[i]).then((res: any) => {});
    // }
  };
  createWorkOrder = (planItem: anyObj) => {
    const workOrder = useProductionWorkOrder();
    console.log("批量生成工单", planItem);

    return new Promise((resolve, reject) => {
      workOrder
        .confirmWorkOrder(planItem)
        .then((res: any) => {
          resolve("");
        })
        .catch((err: any) => {
          reject("");
        });
    });
  };

  // 检查产能
  capacityCheck = (data: any[]) => {
    const routePlan = useBomRoute();
    // const process = useBomProcess();
    const equipUnit = useFactoryEquipment();
    const workOrder = useProductionWorkOrder();
    let devices = new Map(); //设备列表
    let processPlan = new Map(); //工序列表
    let times = new Map(); //计划时间列表map
    let processOherTime = new Map(); //工序的准备时间
    //拿到工序字典
    const dict = useDictionary();
    //循环遍历异步 保证按顺序完成产能查询
    const getDevicesList = async (data: any) => {
      // const promises = data.map(doSearch);
      // await Promise.all(promises);
      // console.log("循环遍历所有异步操作都将以并行方式执行", promises);
      //以下 非并行
      for (const item of data) {
        await doSearch(item);
      }
    };
    async function doSearch(item: any) {
      return new Promise((resolve, reject) => {
        //区分人工与机加工工序
        if (
          item.type !== null &&
          dict.processType["type"][item.type - 0] === "人工"
        ) {
          console.log("工序人工类型");
          resolve("");
        } else if (
          item.type !== null &&
          dict.processType["type"][item.type - 0] === "机加工"
        ) {
          console.log("工序机加工类型");
          //使用工序id查询对应设备
          if (!processPlan.has(item.processId)) {
            equipUnit
              .getEquipmentByRole({
                processIds: [item.processId],
                pageSize: 1000,
              })
              .then(async (res: any) => {
                processPlan.set(item.processId, true);
                devices.set(item.processId, res);
                console.log("devices", devices);
                //遍历设备列表下该工单计划时间段所有产能
                if (res.length > 0) {
                  const getWorkOrderList = async (data: any) => {
                    const promises = data.map(getTime);
                    await Promise.all(promises);
                    console.log("promises", promises);
                    resolve("");
                  };
                  //遍历设备获取该设备下的工单数据
                  function getTime(order: any) {
                    return new Promise((resolve, reject) => {
                      workOrder
                        .getPlanOrderList({
                          pageSize: 10000,
                          startTime: item.startTime,
                          endTime: item.endTime,
                          equipmentCode: order.equipmentCode,
                        })
                        .then((result: any) => {
                          console.log("result", result);
                          let newRes = _.cloneDeep(result.rows);
                          for (let i = 0; i < newRes.length; i++) {
                            //!遍历每个工单拿到最晚时间
                            newRes[i].endTime =
                              new Date(newRes[i].endTime).getTime() +
                              (item.prepareTime +
                                item.afterTime +
                                item.productTime) *
                                60 *
                                1000;
                          }
                          //排序
                          let compare = function (obj1: anyObj, obj2: anyObj) {
                            let res1 = obj1.endTime;
                            let res2 = obj2.endTime;
                            if (res1 < res2) {
                              return -1;
                            } else if (res1 > res2) {
                              return 1;
                            } else {
                              return 0;
                            }
                          };
                          newRes = newRes.sort(compare);
                          console.log("换算时间后的计划结束时间", newRes);
                          // newRes[newRes.length - 1].endTime = timeFormat(
                          //   newRes[newRes.length - 1].endTime
                          // );
                          resolve(newRes[newRes.length - 1]);
                        });
                    });
                  }
                  getWorkOrderList(res);
                } else {
                  resolve("");
                }
              })
              .catch((err: any) => {
                reject("");
              });
          } else {
            //重复工序不需要再查询设备列表
          }
        } else {
          //没有类型
          console.log("工序没有类型");
          resolve("");
        }
      });
    }
    getDevicesList(data);
  };

  /**
   * 打开表单
   * @param operate 操作:add=添加,edit=编辑
   * @param operateIds 被操作项的数组:add=[],edit=[1,2,...]
   */
  toggleForm = (operate = "", operateIds: string[] | TableRow = []) => {
    if (this.runBefore("toggleForm", { operate, operateIds }) === false) return;
    if (this.form.ref) {
      this.form.ref.resetFields();
    }
    //编辑表单
    if (operate == "edit") {
      if (!operateIds.length) {
        return false;
      }
      this.requestEdit((operateIds as string[])[0]);
      //添加表单
    } else if (operate == "add") {
      this.form.items = Object.assign({}, this.form.defaultItems);
    } else if (operate == "itemAdd") {
      this.form.items = Object.assign({}, operateIds as TableRow);
      console.log("itemAdd", this.form.items);
    } else if (operate == "inspection") {
      //巡检
      console.log("巡检", this.table.selection);
    } else if (operate == "upload") {
      //上传文件
      console.log("上传文件", this.table.selection);
    }

    this.form.operate = operate;
    if (this.api.controllerUrl !== "/system/site") {
      //站点管理不进行批量新增
      this.form.operateIds = operateIds as string[];
    }
    this.runAfter("toggleForm", { operate, operateIds });
  };

  //提交表单
  onSubmit = (formEl: InstanceType<typeof ElForm> | undefined = undefined) => {
    if (
      this.runBefore("onSubmit", {
        formEl: formEl,
        operate: this.form.operate!,
        items: this.form.items!,
      }) === false
    )
      return;

    console.log("this.form.items", this.form.items);
    Object.keys(this.form.items!).forEach((item) => {
      if (this.form.items![item] === null) {
        delete this.form.items![item];
      }
    });

    // 表单验证通过后执行的api请求操作
    const submitCallback = () => {
      this.form.submitLoading = true;
      this.api
        .postData(this.form.operate!, this.form.items!)
        .then((res) => {
          this.onTableHeaderAction("refresh", {});
          this.form.submitLoading = false;
          this.form.operateIds?.shift();
          if (this.form.operateIds!.length > 0) {
            this.toggleForm("edit", this.form.operateIds);
          } else {
            this.toggleForm();
          }
          this.runAfter("onSubmit", { res });
        })
        .catch(() => {
          this.form.submitLoading = false;
        });
    };

    if (formEl) {
      this.form.ref = formEl;
      formEl.validate((valid) => {
        if (valid) {
          submitCallback();
        }
      });
    } else {
      submitCallback();
    }
  };

  /**
   * 表格内的事件统一响应
   * @param event 事件:selection-change=选中项改变,page-size-change=每页数量改变,current-page-change=翻页,sort-change=排序
   * @param data 携带数据
   */
  onTableAction = (event: string, data: anyObj) => {
    if (this.runBefore("onTableAction", { event, data }) === false) return;
    const actionFun = new Map([
      [
        "selection-change",
        () => {
          this.table.selection = data as TableRow[];
        },
      ],
      [
        "page-size-change",
        () => {
          this.table.filter!.pageSize = data.pageSize;
          this.comSearch.form = Object.assign(
            this.comSearch.form,
            this.table.filter
          );
          this.getList("");
        },
      ],
      [
        "current-page-change",
        () => {
          this.table.filter!.pageNum = data.pageNum;
          this.comSearch.form = Object.assign(
            this.comSearch.form,
            this.table.filter
          );
          this.getList("");
        },
      ],
      [
        "sort-change",
        () => {
          let newOrder: string | undefined;
          if (data.prop && data.order) {
            newOrder = data.prop + "," + data.order;
          }
          if (newOrder != this.table.filter!.order) {
            this.table.filter!.isAsc = data.order;
            this.table.filter!.orderByColumn = data.prop;
            this.comSearch.form = Object.assign(
              this.comSearch.form,
              this.table.filter
            );
            this.getList("");
          }
        },
      ],
      [
        "default",
        () => {
          console.warn("未定义操作");
        },
      ],
    ]);

    const action = actionFun.get(event) || actionFun.get("default");
    action!.call(this);
    return this.runAfter("onTableAction", { event, data });
  };

  /**
   * 表格顶栏按钮事件统一响应
   * @param event 事件:refresh=刷新,edit=编辑,delete=删除,quick-search=快速查询
   * @param data 携带数据
   */
  onTableHeaderAction = (event: string, data: any) => {
    if (this.runBefore("onTableHeaderAction", { event, data }) === false)
      return;
    const equipUnit = useFactoryEquipment();
    const bom = useBomM();
    const equipClassType = useFactoryEquipmenClass();
    const equipSchedule = useFactorySchedule();
    const purchase = useStoreWarePurchase(); //采购单
    const supplier = useSupplierInfo(); //供应商
    const actionFun = new Map([
      [
        "refresh",
        () => {
          console.log("触发了刷新事件", this.api.controllerUrl);
          this.table.data = [];
          //菜单列表刷新
          this.getList(this.api.controllerUrl);
        },
      ],
      [
        "refreshistory",
        () => {
          console.log("触发了刷新事件", this.api.controllerUrl);
          this.table.data = [];
          //菜单列表刷新
          this.getHistory(this.api.controllerUrl, "");
        },
      ],
      [
        "back",
        () => {
          console.log("触发了返回大屏事件", this.api.controllerUrl);
          router.push({
            path: "/admin/Bigboard/bigboardFirst",
          });
        },
      ],
      [
        "inspection",
        () => {
          console.log("触发了巡检事件", this.api.controllerUrl);
          this.toggleForm("inspection", this.getSelectionIds());
        },
      ],
      [
        "add",
        () => {
          console.log("触发了添加事件", this.api, window.location.hash);
          if (
            window.location.hash === "#/admin/system/equipment" &&
            this.api.controllerUrl === "/system/equipment" &&
            JSON.stringify(equipUnit.stationInfo) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘手动添加’ 请在侧边栏选择相应的节点",
            });
          } else if (
            this.api.controllerUrl === "/system/route" &&
            JSON.stringify(bom.bomInfo) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘手动添加’ 请在侧边栏选择相应的节点",
            });
          } else if (
            this.api.controllerUrl === "/system/classType" &&
            JSON.stringify(equipClassType.equipmentScheduleInfo) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘设备排班’ 请在侧边栏选择设备节点",
            });
          } else if (
            this.api.controllerUrl === "/system/workDay" &&
            JSON.stringify(equipSchedule.equipmentScheduleInfo) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘工厂日历’ 请在侧边栏选择部门节点",
            });
          } else if (
            this.api.controllerUrl === "/system/purchaseList" &&
            JSON.stringify(purchase.purchaseMaterialInfo) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘采购订单’ 请在侧边栏选择采购物料",
            });
          } else if (
            this.api.controllerUrl === "/system/supplierMainBrand" &&
            JSON.stringify(supplier.info) == "{}"
          ) {
            ElNotification({
              type: "warning",
              message: "‘新增供应链产品’ 请在侧边栏选择相应供应商",
            });
          } else {
            this.toggleForm("add");
          }
        },
      ],
      [
        "edit",
        () => {
          console.log("触发了编辑事件");
          this.toggleForm("edit", this.getSelectionIds());
        },
      ],
      [
        "remove",
        () => {
          console.log("触发了删除事件");
          this.postDel(this.getSelectionIds());
        },
      ],
      [
        "unfold",
        () => {
          if (!this.table.ref) {
            console.warn(
              "折叠/展开失败，因为tableRef未定义，请在onMounted时赋值tableRef"
            );
            return;
          }
          this.table.expandAll = data.unfold;
          //调用table组件内暴露出去的unFoldAll方法
          this.table.ref.unFoldAll(data.unfold);
        },
      ],
      [
        "upload",
        () => {
          console.log("触发了上传文件事件", this.api.controllerUrl);
          this.toggleForm("upload");
        },
      ],
      [
        "export",
        () => {
          console.log("触发了导出文件事件", this.api.controllerUrl);
          this.exportTable(this.getSelectionIds());
        },
      ],
      [
        "quick-search",
        () => {
          console.log("触发了搜索");
          this.table.filter!.quick_search = data.keyword;
          this.getIndex("");
        },
      ],
      [
        "change-show-column",
        () => {
          const columnKey = getArrayKey(this.table.column, "prop", data.field);
          this.table.column[columnKey].show = data.value;
        },
      ],
      [
        "placeOrder",
        () => {
          console.log("批量下单&&前并检查产能", this.api.controllerUrl);
          this.batchOrder(this.getSelectionIds());
        },
      ],
      [
        "default",
        () => {
          console.warn("未定义操作");
        },
      ],
    ]);

    const action = actionFun.get(event) || actionFun.get("default");
    action!.call(this);
    return this.runAfter("onTableHeaderAction", { event, data });
  };

  mount = () => {
    if (this.runBefore("mount") === false) return;
    this.activate = true;
    const { proxy } = useCurrentInstance();
    /**
     * 表格内的按钮响应
     * @param name 按钮name
     * @param row 被操作行数据
     */
    proxy.eventBus.on(
      "onTableButtonClick",
      (data: { name: string; row: TableRow }) => {
        if (!this.activate) return;
        if (data.name == "edit") {
          this.toggleForm("edit", [data.row[this.table.pk!]]);
        } else if (data.name == "remove") {
          this.postDel([data.row[this.table.pk!]]);
        } else if (
          data.name == "itemAdd" &&
          this.api.controllerUrl == "/system/menu"
        ) {
          //侧边栏为新增按钮，打开表单
          let temp: TableRow = {
            menuId: undefined,
            parentId: data.row.menuId,
            menuName: undefined,
            icon: undefined,
            menuType:
              data.row.menuType == "M"
                ? "C"
                : data.row.menuType == "C"
                ? "F"
                : "",
            orderNum: undefined,
            isFrame: "1",
            isCache: "0",
            visible: "0",
            status: "0",
          };
          this.toggleForm("itemAdd", temp);
        } else if (
          data.name == "itemAdd" &&
          (this.api.controllerUrl == "/system/region" ||
            this.api.controllerUrl == "/system/dept" ||
            this.api.controllerUrl == "/system/workshop" ||
            this.api.controllerUrl == "/system/bom")
        ) {
          //区域管理/部门管理给每个数据新增的时候触发
          let temp: TableRow = {
            parentId:
              this.api.controllerUrl == "/system/region"
                ? data.row.areaId
                : this.api.controllerUrl == "/system/dept"
                ? data.row.deptId
                : data.row.id,
          };
          this.toggleForm("itemAdd", temp);
        } else if (
          //站点管理
          data.name == "itemAdd" &&
          this.api.controllerUrl == "/system/site"
        ) {
          console.log("站点管理", data);
          let temp: TableRow = {
            // parentName: data.row.siteName,
            parentId: data.row.siteId,
            siteOrder: 1,
            siteType: 0, //0为地区类型
          };
          this.toggleForm("itemAdd", temp);
        } else if (
          data.name == "itemAdd" &&
          this.api.controllerUrl == "/system/route"
        ) {
          console.log("父级物料", data.row);
          let temp: TableRow = {
            previousProcess: data.row.processName,
            previousProcessId: data.row.id,
            materialType: data.row.type,
          };
          this.toggleForm("itemAdd", temp);
        } else {
        }
      }
    );
    /**
     * 通用搜索响应
     * @param comSearchData 通用搜索数据
     */
    //!待改
    proxy.eventBus.on("onTableComSearch", (data: comSearchData) => {
      if (!this.activate) return;
      // this.table.filter!.search = data;
      //!把私类改成了公共类
      if (
        JSON.stringify(this.comSearch.form.params) !== "{}" &&
        this.comSearch.form.params
      ) {
        console.log("getSearch", this.comSearch.form);

        this.getSearch("");
      } else {
        console.log("getList");
        this.getList("");
      }
    });

    /**
     * 表格内的字段操作响应
     * @param value 修改后的值
     * @param row 被操作行数据
     * @param field 被操作字段名
     */
    proxy.eventBus.on(
      "onTableFieldChange",
      (data: {
        value: any;
        row: TableRow;
        field: keyof TableRow;
        render: string;
      }) => {
        if (!this.activate) return;
        if (data.render == "switch" || "switchAccess") {
          data.row.loading = true;
          if (
            this.api.controllerUrl === "/system/user" ||
            this.api.controllerUrl === "/system/role"
          ) {
            //如果是用户管理切换状态
            this.api
              .switch("changeStatus", {
                [this.table.pk!]: data.row[this.table.pk!],
                [data.field]: data.value,
              })
              .then(() => {
                data.row.loading = false;
                data.row[data.field] = data.value;
              })
              .catch(() => {
                data.row.loading = false;
              });
          } else if (this.api.controllerUrl === "/system/equipment") {
            //设备激活需要将state变为0在线
            console.log("data.value", data.value, typeof data.value);
            this.api
              .postData("edit", {
                [this.table.pk!]: data.row[this.table.pk!],
                openState: data.value,
                state: Number(data.value) ? 0 : 1,
              })
              .then(() => {
                data.row.loading = false;
                data.row[data.field] = data.value;
                data.row.state = Number(data.value) ? 0 : 1;
              })
              .catch(() => {
                data.row.loading = false;
              });
          } else {
            this.api
              .postData("edit", {
                [this.table.pk!]: data.row[this.table.pk!],
                [data.field]: data.value,
              })
              .then(() => {
                data.row.loading = false;
                data.row[data.field] = data.value;
              })
              .catch(() => {
                data.row.loading = false;
              });
          }
        }
      }
    );

    onUnmounted(() => {
      // 考虑到 keepalive 在 onMounted、onActivated 时注册事件；onUnmounted、onDeactivated 时注销事件，但并不是最方便的方案，且注销后在全局事件管理中本来就有留存
      // 干脆，不off掉事件，改用 this.activate 来决定事件是否执行
      this.activate = false;
      this.runAfter("mount");
    });

    onActivated(() => {
      this.activate = true;
    });

    onDeactivated(() => {
      this.activate = false;
    });

    // 监听路由变化,响应通用搜索更新
    onBeforeRouteUpdate((to) => {
      this.initComSearch(to.query);
      this.getIndex("");
    });
  };

  /**
   * 通用搜索初始化
   */
  initComSearch = (query: any = {}) => {
    const form: anyObj = {};

    //如果table的cloumn数组为0就返回
    if (this.table.column.length <= 0) {
      return;
    }
    const field = this.table.column;
    //遍历column数组
    for (const key in field) {
      // 如果 通用搜索operator字段为false表示禁用
      if (field[key].operator === false) {
        // 结束本次循环，循环体后续的语句不执行 进行下一次循环体语句的执行
        continue;
      }
      //form表单的prop属性 与rules组合的
      const prop = field[key].prop;
      //条件搜索为undefined时 赋值为等于
      if (typeof field[key].operator == "undefined") {
        field[key].operator = "=";
      }
      //如果存在prop需要验证的字段
      if (prop) {
        //RANGE 范围，将生成两个输入框 以输入最小值和最大值
        if (
          field[key].operator == "RANGE" ||
          field[key].operator == "NOT RANGE"
        ) {
          // if (prop !== "reportTime") {
          //   form[prop] = "";
          //   //新建两个form表单属性
          //   form[prop + "-start"] = "";
          //   form[prop + "-end"] = "";
          // }
        } else if (
          field[key].operator == "NULL" ||
          field[key].operator == "NOT NULL"
        ) {
          // 是否为NULL，将生成单个复选框 新建复选框表单属性
          form[prop] = false;
        } else {
          //新建普通属性 值为字符串
          form[prop] = "";
        }
        // 初始化来自query中的默认值
        /**
         * this.table.acceptQuery为true表示接受url的query参数并自动触发通用搜索
         */
        if (this.table.acceptQuery && typeof query[prop] != "undefined") {
          //当query[prop]为undefined或null返回""
          const queryProp = (query[prop] as string) ?? "";
          //RANGE 范围，将生成两个输入框 以输入最小值和最大值
          if (
            field[key].operator == "RANGE" ||
            field[key].operator == "NOT RANGE"
          ) {
            const range = queryProp.split(",");
            //如果通用搜索为日期选择器
            if (field[key].render == "datetime") {
              if (range && range.length >= 2) {
                form[prop + "-default"] = [
                  new Date(range[0]),
                  new Date(range[1]),
                ];
              }
            } else {
              //新增最大与最小的表单属性
              form[prop + "-start"] = range[0] ?? "";
              form[prop + "-end"] = range[1] ?? "";
            }
          } else if (
            field[key].operator == "NULL" ||
            field[key].operator == "NOT NULL"
          ) {
            //如果为null 将生成单个复选框 新建复选框表单属性
            form[prop] = queryProp ? true : false;
          } else if (field[key].render == "datetime") {
            form[prop + "-default"] = new Date(queryProp);
          } else {
            form[prop] = queryProp;
          }
        }
        // 通用搜索数据-需要响应性 new Map().set 设置新属性
        this.comSearch.fieldData.set(prop, {
          operator: field[key].operator,
          render: field[key].render,
          comSearchRender: field[key].comSearchRender,
        });
      }
    }

    //遍历完之后
    // 接受query再搜索

    if (this.table.acceptQuery) {
      //新数组
      const comSearchData: comSearchData[] = [];
      //遍历query
      for (const key in query) {
        console.log("query,query", query);

        //将comSearch通用搜索数据与query有关的值获取
        const fieldDataTemp = this.comSearch.fieldData.get(key);
        console.log("this.comSearch", this.comSearch);

        comSearchData.push({
          field: key,
          val: query[key] as string,
          operator: fieldDataTemp.operator,
          render: fieldDataTemp.render,
        });
        console.log("comSearchData", comSearchData);
      }
      // 字段搜索,快速搜索,分页等数据 {}
      this.table.filter!.search = comSearchData;
    }
    //通用搜索的from表单合并
    this.comSearch.form = Object.assign(
      this.comSearch.form,
      form,
      this.table.filter
    );
  };
}
